<!--
生产单-产品列表页
-->

<template>
  <a-modal
    :title="title || '产品列表'"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24" v-if="false">
              <a-form-item label="订单ID">
                <a-input v-model="queryParam.orderId" placeholder="请输入订单ID"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button v-if="viewState == 'productionPool' && emsOrder.isOverseasStore == 'N'"
                  icon="plus"
                  type="primary"
                  @click="$refs.productAddForm.add(emsOrder)">新增产品
        </a-button>
        <a-button v-if="viewState == 'productionPool' && emsOrder.isOverseasStore == 'Y'"
                  icon="plus"
                  type="primary"
                  @click="$refs.overseasProductAddForm.add(emsOrder)">添加海外仓产品
        </a-button>
        <a-button v-if="viewState == 'inProduction'"
                  type="primary"
                  @click="$refs.productAddForm.add(emsOrder)">完成生产
        </a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :columns="columnsDynamic"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.code"
        :rowSelection="null && { selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :showPagination="false"
      >

        <template slot="thisCompleteNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.thisCompleteNumber" :step="1" :min="0" style="width: 67px;"/>
        </template>

        <span slot="actionCommon" slot-scope="text, record" v-if="extra.title != '采购单入库记录'">
<!--    查进度明细时，需要筛选出源引过该记录的订单      -->
          <a v-if="extra.title != '入库记录'"
            @click="$refs.orderIndexModal.show(Object.assign({sourceOrderMaterialIds:record.orderMaterialId},record),
           '订单列表', 'common')">进度明细</a>

<!--    UI上显示的是订单物料列表,而不是订单.因此还要循环用一下本页面      -->
          <a v-else
            @click="$refs.orderMaterialIndexModal.show(
            {
              sourceOrderMaterialId: record.orderMaterialId,
              orderType: $businessEnum.ORDER_TYPE_ENUM.inOrder.id
            },
            { title:'采购单入库记录', viewState: 'orderMaterialCommon' } )">进度明细</a>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="$refs.editForm.edit(record)">产品编辑</a>
          <!--          <a-divider type="vertical"/>-->
          <!--          <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">-->
          <!--            <a>删除</a>-->
          <!--          </a-popconfirm>-->
        </span>

        <span slot="actionInProduction" slot-scope="text, record">
          <a @click="$refs.productDetailForm.add(record)">产品明细</a>
        </span>
      </s-table>

      <!--      <add-form ref="addForm" @ok="handleOk"/>-->
      <edit-form ref="editForm" @ok="handleOk"/>
      <ems-material-index1 ref="emsMaterialIndex1" :on-row-selected="onEmsMaterialIndex1Selected"/>
      <product-add-form ref="productAddForm" @ok="handleOk"/>
      <product-edit-form ref="productEditForm" @ok="handleOk"/>
      <product-detail-form ref="productDetailForm" @ok="handleOk"/>
      <order-index-modal ref="orderIndexModal" @ok="handleOk"/>
      <overseas-product-add-form ref="overseasProductAddForm" @ok="handleOk"/>

      <!--  关联物料页面  -->
      <order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk"/>

    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, del, add} from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
// import {page, del} from '@/api/modular/main/emsorder/emsOrderManage'
// import addForm from '../emsordermaterial/emsOrderMaterialAddForm'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'
import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'
import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'
import productDetailForm from '@/views/main/emsorder/emsOrderProductDetailForm'
import orderIndexModal from '@/views/main/emsorder/emsOrderIndexModal'
import overseasProductAddForm from '@/views/main/productionCenter/productionOrderPool/overseasProductAddForm'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'

export default {
  components: {
    STable,
    // addForm,
    editForm,
    materialForm,
    emsMaterialIndex1,
    productAddForm,
    productEditForm,
    productDetailForm,
    orderIndexModal,
    overseasProductAddForm,
    // 为了解决与该控件的循环引用,所以使用如下方法
    orderMaterialIndexModal: () => import('@/views/main/emsordermaterial/emsOrderMaterialIndexModal'),
  },

  data() {
    return {
      title: null,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          res.data.rows.forEach(value => {
            value.thisCompleteNumber = 0
          })
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      visible: false,
      confirmLoading: false,
      emsOrder: null,
      viewState: '',
      extra: {},
    }
  },
  computed: {
    token() {
      return Vue.ls.get(ACCESS_TOKEN)
    },
    columnsDynamic() {
      let vs = this.viewState
      if (vs == 'productionPool') {
        // 生产单池中(生产单草稿阶段)
        this.advanced = false
        return [
          {
            title: '产品编号',
            dataIndex: 'materialCode'
          },
          {
            title: '产品别名',
            dataIndex: 'materialName'
          },
          {
            title: '需求数',
            dataIndex: 'number'
          },
          {
            title: '序号', width:'80px',
            dataIndex: 'extend1'
          },
          {
            title: '软件版本号',
            dataIndex: 'extend2'
          },
          {
            title: '更新时间',
            dataIndex: 'updateTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: {customRender: 'action'}
          }
        ]
      } else if (vs == 'inProduction') {
        // 生产单进行中
        this.advanced = true
        return [
          {
            title: '产品编号',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '产品名称',
            dataIndex: 'materialName'
          },
          {
            title: '数量',
            dataIndex: 'number'
          },
          {
            title: '已入库数量',
            dataIndex: ''
          },
          {
            title: '待入库数量',
            customRender: (text, record, index) => `${record.number}`
          },
          {
            title: '待生产数量',
            dataIndex: ''
          },
          {
            title: '本次完成生产数量',
            scopedSlots: {customRender: 'thisCompleteNumber'}
          },
          {
            title: '序列号',
            dataIndex: ''
          },
          {
            title: '备注',
            dataIndex: 'remark'
          },
          {
            title: '操作',
            width: '150px',
            scopedSlots: {customRender: 'actionInProduction'}
          }
        ]
      } else if (vs == 'orderMaterialCommon') {
        return [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          ...this.columnsMaterialProperty,
          {
            title: '操作',
            width: '150px',
            scopedSlots: {customRender: 'actionCommon'}
          }
        ]
      } else {
        return []
      }
    },
    columnsMaterialProperty() {
      let result = [
        {
          title: '名称',
          dataIndex: 'materialName'
        },
        {
          title: '订单号',
          dataIndex: 'orderNumber',
          ellipsis: true
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          customRender: (text, record, index) => {
            let otEnum = this.$util.findOrderTypeById(text)
            return otEnum? otEnum.name : '未知类型'
          }
        },
        {
          title: '料号',
          dataIndex: 'materialCode'
        },
        {
          title: '图片',
          dataIndex: 'image',
          customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
        },
        {
          title: '需求数量',
          dataIndex: 'number'
        },
        {
          title: '已入库数量',
          dataIndex: 'completedNumber'
        },
        {
          title: '状态',
          dataIndex: 'executeStatus',
          customRender: (text, record, index) => {
            let es = this.$util.findExecuteStatusById(text)
            return es ? es.name : '未知状态'
          }
        },
        {
          title: '备注',
          dataIndex: 'remark'
        },
      ]

      if (!this.extra) {
        return result
      }

      if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.material.id) {
        result = [
          {
            title: '原料编号',
            dataIndex: 'materialCode'
          },
          {
            title: '原料名称',
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            dataIndex: ''
          },
          {
            title: '图片',
            dataIndex: 'image',
            customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
          },
          {
            title: '需求数量',
            dataIndex: 'number'
          },
          {
            title: '已入库数量',
            dataIndex: 'completedNumber'
          },
          {
            title: '状态',
            dataIndex: 'executeStatus',
            customRender: (text, record, index) => {
              let es = this.$util.findExecuteStatusById(text)
              return es ? es.name : '未知状态'
            }
          },
        ]
      } else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.product.id) {
        result = [
          {
            title: '产品编号',
            dataIndex: 'materialCode'
          },
          {
            title: '产品名称',
            dataIndex: 'materialName'
          },
        ]
      } else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.packing.id) {
        result = [
          {
            title: '包材编号',
            dataIndex: 'materialCode'
          },
          {
            title: '包材名称',
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            dataIndex: 'materialModelNumber'
          },
          {
            title: '尺寸',
            dataIndex: 'extend1'
          },
          {
            title: '图片',
            dataIndex: 'image',
            customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
          },
          {
            title: '需求数量',
            dataIndex: 'number'
          },
          {
            title: '已入库数量',
            dataIndex: 'completedNumber'
          }
        ]
      } else if (this.extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.cable.id) {
        result = [
          {
            title: '线缆编号',
            dataIndex: 'materialCode'
          },
          {
            title: '线缆名称',
            dataIndex: 'materialName'
          },
          {
            title: '颜色',
            dataIndex: 'extend3'
          },
          {
            title: '规格',
            dataIndex: 'extend4'
          },
          {
            title: '图片',
            dataIndex: 'image',
            customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
          },
          {
            title: '需求数量',
            dataIndex: 'number'
          },
          {
            title: '已入库数量',
            dataIndex: 'completedNumber'
          }
        ]
      }
      return result
    }
  },
  methods: {
    show(record, extra) {
      this.visible = true
      this.emsOrder = record
      this.title = extra.title
      this.viewState = extra.viewState
      this.extra = extra
      this.queryParam = extra || {}

      this.queryParam.orderId = record.orderId
      this.queryParam.sourceOrderMaterialId = record.sourceOrderMaterialId
      this.queryParam.materialType = record.isOverseasStore == 'N' ? this.$businessEnum.MATERIAL_TYPE_ENUM.product.id : this.$businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id
      this.queryParam.pageSize = -1
      setTimeout(() => {
        this.handleOk()
        this.$refs.table.clearSelected()
      }, 100)
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSubmit() {
    },
    handleCancel() {
      this.visible = false
    },
    onEmsMaterialIndex1Selected(materialRow) {
      // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
      // debugger
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      // 需要调用接口往订单中添加物料
      let _emsOrder = Object.assign({}, this.emsOrder)
      _emsOrder.orderMaterials = []
      let orderMaterial = {
        orderMaterialId: '',
        orderId: _emsOrder.orderId,
        bomId: '0',  // 单独选择原料时没有BOMID
        materialId: materialId,
        number: 1,
        completedNumber: 0,
        executeStatus: '0',
        executeProgress: '0',
        status: '0',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      }
      _emsOrder.orderMaterials.push(orderMaterial)
      add(orderMaterial).then(res => {
        if (res.success) {
          this.$message.success('新增成功')
          // this.handleCancel()
          // this.$emit('ok', values)
          this.$refs.table.refresh()
        } else {
          this.$message.info('新增失败：' + res.message)
        }
      })
      // 然后刷新table控件
    },
    imageURLFormat(text) {
      return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
